package by.brest.bspc.web.controllers;

import by.brest.bspc.domain.Grade;
import by.brest.bspc.domain.Student;
import by.brest.bspc.service.StudentRepositoryService;
import by.brest.bspc.web.TreeFileFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;
import java.util.Map;

/**
 * Controller for the formation of the summary report.
 *
 * @date: 07.10.13 21:05
 * @author: Natallia
 */
@Controller
public class SummaryReportController {
    private static final Logger LOG = LoggerFactory.getLogger(SummaryReportController.class);
    private static final String STATUS_EXPELLED = "expelled";
    private static final String STATUS_ACTIVE = "active";

    @Value("${documentation.directory}")
    private String documentationDirectory;

    @Resource
    StudentRepositoryService studentRepositoryService;

    /**
     * Prepares list of groups for the summary report page.
     *
     * @param model model.
     * @return view name.
     */
    @RequestMapping(value = "/summaryreport")
    public String showSummaryReportPage(Map<String, Object> model) {
        LOG.debug(">> Start showSummaryReportPage method of controller.");

        TreeFileFilter treeFileFilter = new TreeFileFilter(true);
        StringBuilder totalPath = new StringBuilder(documentationDirectory);
        totalPath.append(File.separator + "College" + File.separator + "Current");
        File currentDirectory = new File(totalPath.toString());

        LOG.debug(">> Current directory: " + currentDirectory);

        List<File> documentsDirectoryList = Arrays.asList(currentDirectory.listFiles(treeFileFilter));
        List<String> groupsNamesList = new ArrayList<>();
        for (File subDirectory : documentsDirectoryList) {
            List<File> documentsSubDirectoryList = Arrays.asList(subDirectory.listFiles(treeFileFilter));
            for (File groupDirectory : documentsSubDirectoryList) {
                groupsNamesList.add(groupDirectory.getName());
            }
        }

        LOG.debug(">> Created list of groups: " + groupsNamesList);

        model.put("groupsList", groupsNamesList);
        model.put("studentsList", new ArrayList<Student>());

        return "summaryReport";
    }

    /**
     * Prepares list of students of selected group for the summary report page.
     *
     * @param groupName selected group.
     * @param model     model.
     * @return view name.
     */
    @RequestMapping(value = "/summaryreport/list", method = RequestMethod.POST)
    public String showStudentsList(@RequestParam("groupName") String groupName, Map<String, Object> model) {
        LOG.debug(">> Start showStudentsList method of controller.");

        LOG.debug(">> Parameter of request: groupName = " + groupName);

        int classNumber = studentRepositoryService.getCurrentClassByGroupName(groupName);

        LOG.debug(">> Current class number: " + classNumber);

        Calendar calendar = Calendar.getInstance();
        int month = calendar.get(Calendar.MONTH);
        int semesterNumber = (month == 0 || month >= 8) ? classNumber * 2 - 1 : classNumber * 2;

        LOG.debug(">> Current month: " + month + "; current semester: " + semesterNumber);

        List<Student> studentsList = studentRepositoryService.getStudentsList(groupName, semesterNumber);

        LOG.debug(">> List of students: " + studentsList);

        model.put("studentsList", studentsList);
        model.put("groupsList", new ArrayList<>());
        model.put("semesterNumber", semesterNumber);

        return "summaryReport";
    }

    /**
     * Saves filled list of students of selected group to database.
     *
     * @param id             list of id of students.
     * @param marks          list of marks of students.
     * @param respect        list of respect absenteeism of students.
     * @param direspect      list of direspect absenteeism of students.
     * @param toExpelled     list of id of students, that need to expelled.
     * @param disciplineList list of disciplines.
     * @param semesterNumber semester number.
     * @param model          model.
     * @return redirect to showSummaryReportPage method.
     */
    @RequestMapping(value = "/summaryreport/save", method = RequestMethod.POST)
    public String updateStudentsList(@RequestParam("id") String[] id, @RequestParam("marks") String[] marks,
                                     @RequestParam("respect") String[] respect, @RequestParam("direspect") String[] direspect,
                                     @RequestParam("toExpelled") String[] toExpelled, @RequestParam("disciplineList") String[] disciplineList,
                                     @RequestParam("semesterNumber") String semesterNumber, Map<String, Object> model) {
        LOG.debug(">> Start updateStudentsList method of controller.");

        LOG.debug(">> Parameters of request:");
        LOG.debug(">> id = " + id);
        LOG.debug(">> marks = " + marks);
        LOG.debug(">> respect = " + respect);
        LOG.debug(">> direspect = " + direspect);
        LOG.debug(">> toExpelled = " + toExpelled);
        LOG.debug(">> disciplineList = " + disciplineList);
        LOG.debug(">> semesterNumber = " + semesterNumber);

        Grade grade;
        List<Grade> gradeList;
        Student student;
        List<Student> studentsList = new ArrayList<>();
        List<String> toExpelledList = new ArrayList<>();

        if (toExpelled.length != 0) {
            for (int i = 0; i < toExpelled.length; i++) {
                toExpelledList.add(toExpelled[i]);
            }
        }

        int position = 0;

        for (int i = 0; i < id.length; i++) {

            student = new Student();
            student.setId(id[i]);

            if (toExpelledList.contains(id[i])) {
                student.setStatus(STATUS_EXPELLED);
            } else {
                student.setStatus(STATUS_ACTIVE);
            }

            gradeList = new ArrayList<>();
            for (int j = 0; j < disciplineList.length; j++) {
                grade = new Grade();
                grade.setDisciplineName(disciplineList[j]);
                grade.setSemesterNumber(Integer.parseInt(semesterNumber));
                grade.setMark(Integer.parseInt(marks[j + position]));
                grade.setRespect(Integer.parseInt(respect[j + position]));
                grade.setDirespect(Integer.parseInt(direspect[j + position]));

                gradeList.add(grade);
            }

            LOG.debug(">> Created student: " + student);

            student.setGradeList(gradeList);
            studentsList.add(student);
            position += disciplineList.length;
        }

        studentRepositoryService.updateStudentsList(studentsList);

        model.put("studentsList", new ArrayList<>());
        model.put("groupsList", new ArrayList<>());

        return "redirect:/summaryreport";
    }
}
